package com.dsjy.yf.address.utils;

import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.MediaType;
import org.springframework.util.ResourceUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author whj
 * @version 1.0
 * @date 2021-01-14 17:02
 */
public class DownLoadUtil {
    public static final String TEMPLATE_PATH = ".\\标准字段.xlsx";

    public static void downLoadFile(HttpServletResponse response) throws IOException {
        FileInputStream in = null;
        BufferedInputStream bis = null;
        try {
            File file = ResourceUtils.getFile(TEMPLATE_PATH);
            if (file.exists()) {
                response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("标准模板.xlsx", "UTF-8"));
                response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
                response.flushBuffer();
                in = new FileInputStream(file);
                bis = new BufferedInputStream(in);
                // 实现文件下载
                byte[] buffer = new byte[1024];
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }

            }
        } finally {
            if (in != null) {
                in.close();
            }
            if (bis != null) {
                bis.close();
            }
        }
    }

    /**
     * 获得模板Excel文件(只写)
     * @return
     * @throws IOException
     */
    public static SXSSFWorkbook getModelWorkbool() throws IOException {
        FileInputStream fileInputStream = null;
        SXSSFWorkbook workbook = null;
        try {
            fileInputStream = new FileInputStream(ResourceUtils.getFile(TEMPLATE_PATH));
            workbook = new SXSSFWorkbook(new XSSFWorkbook(fileInputStream), 100);
        } finally {
            if (fileInputStream != null) {
                fileInputStream.close();
            }
        }
        return workbook;
    }

    /**
     * 获得模板Excel文件(只读)
     * @return
     * @throws IOException
     */
    public static XSSFWorkbook getModelWorkboolWithRead() throws IOException {
        FileInputStream fileInputStream = null;
        XSSFWorkbook workbook = null;
        try {
            //ResourceUtils.getFile(TEMPLATE_PATH)
            fileInputStream = new FileInputStream(TEMPLATE_PATH);
            workbook = new XSSFWorkbook(fileInputStream);
        } finally {
            if (fileInputStream != null) {
                fileInputStream.close();
            }
        }
        return workbook;
    }
}
